package com.sxz.sbs.module.client.auth;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nanchen.compresshelper.CompressHelper;
import com.sxz.sbs.R;
import com.sxz.sbs.app.GlideApp;
import com.sxz.sbs.applibrary.component.ClearEditText;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.constant.IntentConstant;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.client.bean.RealNameBean;
import com.sxz.sbs.module.client.bean.UploadFileBean;
import com.sxz.sbs.module.client.presenter.RealNamePresenter;
import com.sxz.sbs.module.client.view.RealNameView;
import com.sxz.sbs.widget.CommonTitle;
import com.tian.photopicker.PhotoPicker;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class RealNameActivity extends BaseActivity<RealNamePresenter> implements RealNameView {

    @BindView(R.id.real_name_name)
    ClearEditText realNameName;
    @BindView(R.id.real_name_type)
    TextView realNameType;
    @BindView(R.id.real_name_number)
    ClearEditText realNameNumber;
    @BindView(R.id.card_front)
    ImageView cardFront;
    @BindView(R.id.card_reverse)
    ImageView cardReverse;
    private OptionsPickerView optionsPickerView;
    private List<String> typeData;
    private int cardType = 1;
    private static final int SELECT_PHOTO_FRONT = 1000;
    private static final int SELECT_PHOTO_REVERSE = 1001;
    /**
     * 正则：护照
     */
    public static final String REGEX_PASSPORT= "^1[45][0-9]{7}|([P|p|S|s]\\d{7})|([S|s|G|g]\\d{8})|([Gg|Tt|Ss|Ll|Qq|Dd|Aa|Ff]\\d{8})|([H|h|M|m]\\d{8,10})$";
    /**
     * 正则：港澳通行证
     */
    public static final String REGEX_HK = "^[HMhm]{1}([0-9]{10}|[0-9]{8})$";
    private int frontId,reverseId;
    private int tag;
    private int customId;
    @Override
    protected void init() {
        customId = getIntent().getIntExtra(IntentConstant.CUSTOM_ID,0);
        new CommonTitle.Builder(this).setTitle("上传身份信息").build().show();
        //typeData = DataServer.getIdCardData();
       // initIdCardPicker();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_real_name;
    }

    @Override
    protected RealNamePresenter createPresenter() {
        return new RealNamePresenter();
    }


    @OnClick({R.id.real_name_type, R.id.card_front, R.id.card_reverse, R.id.btn_submit_auth})
    public void onViewClicked(View view) {
        switch (view.getId()) {
           /* case R.id.real_name_type:
                if (optionsPickerView != null) {
                    optionsPickerView.show();
                }
                break;*/
            case R.id.card_front:
                PhotoPicker.builder().setSelectPhotoCount(1).start(this,SELECT_PHOTO_FRONT);
                break;
            case R.id.card_reverse:
                PhotoPicker.builder().setSelectPhotoCount(1).start(this,SELECT_PHOTO_REVERSE);
                break;
            case R.id.btn_submit_auth:
                if (TextUtils.isEmpty(realNameName.getText().toString())) {
                    ToastUtils.showShort("请输入真实姓名");
                    return;
                }
                if (TextUtils.isEmpty(realNameType.getText().toString())) {
                    ToastUtils.showShort("请选择证件类型");
                    return;
                }
                if (TextUtils.isEmpty(realNameNumber.getText().toString())) {
                    ToastUtils.showShort("请输入证件号码");
                    return;
                }
                switch (cardType) {
                    case 1:
                        if (!RegexUtils.isIDCard15(realNameNumber.getText().toString()) && !RegexUtils.isIDCard18(realNameNumber.getText().toString())) {
                            ToastUtils.showShort("请输入正确的身份证号");
                            return;
                        }
                        break;
                    case 2:
                        if (!Pattern.matches(REGEX_PASSPORT, realNameNumber.getInputValue())) {
                            ToastUtils.showShort("请输入正确的护照号码");
                            return;
                        }
                        break;
                    case 3:
                        if (!Pattern.matches(REGEX_HK, realNameNumber.getInputValue())) {
                            ToastUtils.showShort("请输入正确的港澳通行证");
                            return;
                        }
                        break;
                    default:
                        break;
                }
                if (frontId == 0 || reverseId == 0) {
                    ToastUtils.showShort("证件照不能为空");
                    return;
                }
                HashMap<String,Object> map = HttpParamMap.getParamMap();
                map.put("customId",customId);
                map.put("idcardNum",realNameNumber.getInputValue());
                map.put("customName",realNameName.getText().toString());
                map.put("fontImgId",frontId);
                map.put("backImgId",reverseId);
                mPresenter.submitRealName(map);
                break;
            default:
                break;
        }
    }
    /**
     * 初始化身份选择器
     */
    private void initIdCardPicker() {
        optionsPickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String type = typeData.get(options1).toString();
                realNameType.setText(type);
                switch (options1) {
                    case 0:
                        cardType = 1;
                        break;
                    case 1:
                        cardType =2;
                        break;
                    case 2:
                        cardType = 3;
                        break;
                    default:
                        break;
                }
                optionsPickerView.dismiss();
            }
        }).build();
        optionsPickerView.setPicker(typeData);

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        List<String> result = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PHOTO_FRONT) {
                File file = new File(result.get(0));
                File newFile = new CompressHelper.Builder(this)
                        .setMaxWidth(720)
                        .setMaxHeight(1080)
                        .setQuality(80)
                        .setFileName(System.currentTimeMillis()+"")
                        .setCompressFormat(Bitmap.CompressFormat.JPEG)
                        .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                                Environment.DIRECTORY_PICTURES).getAbsolutePath())
                        .build()
                        .compressToFile(file);
                RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), newFile);
                MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", newFile.getName(), requestFile);
                tag = 0;
                mPresenter.uploadAuth(3,filePart);
            } else if (requestCode == SELECT_PHOTO_REVERSE) {
                File file = new File(result.get(0));
                File newFile = new CompressHelper.Builder(this)
                        .setMaxWidth(720)
                        .setMaxHeight(1080)
                        .setQuality(80)
                        .setFileName(System.currentTimeMillis()+"")
                        .setCompressFormat(Bitmap.CompressFormat.JPEG)
                        .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                                Environment.DIRECTORY_PICTURES).getAbsolutePath())
                        .build()
                        .compressToFile(file);
                RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), newFile);
                MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", newFile.getName(), requestFile);
                tag = 1;
                mPresenter.uploadAuth(3,filePart);
            }
        }
    }

    @Override
    public void onSubmitAuthSuccess() {
        ToastUtils.showShort("提交成功");
        finish();
    }

    @Override
    public void onGetAuthSuccess(RealNameBean data) {

    }

    @Override
    public void onUploadAuthSuccess(UploadFileBean data) {
        if (data != null) {
            if (tag == 0) {
                frontId = data.getId();
                //  正面
                GlideApp.with(this).load(data.getTxt_Url()).into(cardFront);
            } else {
                reverseId = data.getId();
                //  反面
                GlideApp.with(this).load(data.getTxt_Url()).into(cardReverse);
            }
        }
    }
}
